#include "stdafx.h"
#include "Win32File.h"
#include "SmartHandle.h"

const int CWin32File::m_sLevel = 32;
CWin32File::CWin32File()
{
}

CWin32File::~CWin32File()
{
	ResetContext();
}

BOOL CWin32File::Load(LPCTSTR lpPath)
{
	BOOL bRet = FALSE;
	if (lpPath && ::PathFileExists(lpPath))
	{
		WIN32_FIND_DATA win32FileData;
		WIN32_FIND_DATA* pWin32FileData = NULL;
		TCHAR szBuffer[MAX_PATH] = { 0 };
		TCHAR szPath[MAX_PATH] = { 0 };
		
		StringCchCopy(szBuffer, MAX_PATH, lpPath);
		StringCchCat(szBuffer, MAX_PATH, _T("\\*.*"));

		HANDLE hFile = ::FindFirstFile(szBuffer, &win32FileData);

		if (hFile != INVALID_HANDLE_VALUE)
		{
			do 
			{	
				if (_tcscmp(win32FileData.cFileName, _T("..")) != 0 && _tcscmp(win32FileData.cFileName, _T(".")) != 0)
				{
					if (win32FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
						StringCchPrintf(szPath, MAX_PATH , _T("%s\\%s"), lpPath, win32FileData.cFileName);
						Load(szPath);
					}
					else
					{
						BOOL bAdd = TRUE;
						for (itePfunFileFilterType ite = m_vecPfunFileFilter.begin(); ite != m_vecPfunFileFilter.end(); ite++)
						{
							if (*ite)
							{
								bAdd = (*(*ite))(&win32FileData, lpPath);
							}
						}

						if (bAdd)
						{
							pWin32FileData = new WIN32_FIND_DATA;
							if (pWin32FileData)
							{
								*pWin32FileData = win32FileData;
								m_vecWin32FindData.push_back(pWin32FileData);
							}
						}
					}
				}
			} while (::FindNextFile(hFile, &win32FileData));
			
			bRet = TRUE;
			::FindClose(hFile);
		}
	}
	
	return bRet;
}

VOID CWin32File::ResetContext()
{
	for(iteWin32FindDataType ite = m_vecWin32FindData.begin(); ite != m_vecWin32FindData.end(); ite++)
	{
		if (*ite)
		{
			delete (*ite);
			*ite = NULL;
		}
	}
	m_vecWin32FindData.clear();
	m_vecPfunFileFilter.clear();
}

VOID CWin32File::AddFileFilter(PFUN_File_Filter pFunFileFilter)
{
	m_vecPfunFileFilter.push_back(pFunFileFilter);
}

